#import "TodayViewController.h"
#import "TodayViewController.h"
#import "QinzTimeLine.h"
#import "TimeLineModel.h"
#import <UIKit/UIKit.h>
#import "Masonry.h"
#import "../view/UIImage.h"
#import "../model/headimageModel.h"

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

@interface TodayViewController ()

@property (nonatomic, strong) QinzTimeLine *timeLine;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) NSMutableArray *dateArr;
@property (nonatomic, strong) NSMutableArray *monthArr;
@property (nonatomic, strong) NSMutableArray *yearArr;
@property (nonatomic,strong) UIView *SearchTopview;
@property (nonatomic,weak) UIButton *Selectbutton;
@property (nonatomic, strong) UIView *eventview;
@property (nonatomic, strong) UITextView *encourageTextView;
@property (nonatomic, strong) UIView *warnView;
@property (nonatomic, strong) UITextView *warnTextView;
@property (nonatomic, strong) NSDictionary *dailyEventDictionary;
@property (nonatomic, strong) NSDictionary *oneTimeEventDictionary;
@property (nonatomic, strong) NSDictionary *weekEventDictionary;
@property (nonatomic, strong) NSMutableArray *dateBtns;
@property (nonatomic, strong) NSMutableArray *weekBtns;
@property (nonatomic, strong) NSString *firstOneTimeEvent;
@property (nonatomic, strong) NSString *userID;
@property (nonatomic, strong) UIView *notlogin_pic;
@property (nonatomic, strong) UILabel *notlogin_label;
@property (nonatomic, strong) UITextView *firstOneTimeEventView;
@property (nonatomic, strong) NSString* serverUrl;
@property (nonatomic, strong) UIButton *lastWeekBtn;
@property (nonatomic, strong) UIButton *nextWeekBtn;
@property NSInteger weekEventCount;
@property NSInteger dailyEventCount;
@property NSInteger oneTimeEventCount;
@property NSInteger now_year;
@property NSInteger now_month;
@property NSInteger now_day;
@property NSInteger now_week;


@property (nonatomic, strong)NSMutableArray* btnWhichDay;
@property (nonatomic, strong)NSMutableArray* btnWhichMonth;
@property (nonatomic, strong)NSMutableArray* btnWhichYear;

@end

@implementation TodayViewController

- (UIView *)SearchTopview{
    if (_SearchTopview == nil) {
        _SearchTopview = [[UIView alloc] init];
        _SearchTopview.frame = CGRectMake(0, 50, SCREEN_WIDTH, 100);
        
    }
    
    return _SearchTopview;
    
}

- (void)decreaseWeek:(UIButton*) Btn {
    [self changeDateBtns:-1];
}

- (void)increaseWeek:(UIButton*) Btn {
    [self changeDateBtns:1];
}

- (void)SelectBtnSearch:(UIButton *)Btn{
    if (!Btn.isSelected) {
        self.Selectbutton.selected = !self.Selectbutton.selected;
        self.Selectbutton.backgroundColor = [UIColor whiteColor];
        Btn.selected = !Btn.selected;
        Btn.backgroundColor = [UIColor colorWithRed:116.0/255 green:104.0/255 blue:190.0/255 alpha:1];
        self.Selectbutton = Btn;
        
        self.now_day = Btn.titleLabel.text.integerValue;
        self.now_month = [self.btnWhichMonth[Btn.tag] intValue];
        self.now_year = [self.btnWhichYear[Btn.tag] intValue];
        NSLog(@"now_month is %ld\nnow_year is %ld\n", self.now_month, self.now_year);
        
        int res = 1;
        for (int i = 0; i < 7; i++) {
            if (((UIButton*)_dateBtns[i]).titleLabel.text.integerValue == self.now_day) {
                res = i;
                break;
            }
        }
        
        self.now_week = res + 1;
        
    }
    
    self.now_day = Btn.titleLabel.text.integerValue;
    self.now_month = [self.btnWhichMonth[Btn.tag] intValue];
    self.now_year = [self.btnWhichYear[Btn.tag] intValue];
    
    [self.dataArr removeAllObjects];
    [self getDailyDatas];
    [self getOnetimeDatas];
    [self getWeekDatas];
    // [self getWeekDatas];
    [self.dataArr sortUsingComparator:^NSComparisonResult(TimeLineModel *c1, TimeLineModel *c2) {
        NSComparisonResult result = [c1.time compare:c2.time];
        return result;
    }];
    
    [self.timeLine removeFromSuperview];
    self.timeLine = [[QinzTimeLine alloc]init];
    [self.timeLine setSuperView:self.eventview DataArr:self.dataArr];
    self.firstOneTimeEventView.text = self.firstOneTimeEvent;
    
    self.navigationItem.title = [NSString stringWithFormat:@"%ld.%ld", (long)self.now_year, (long)self.now_month];
    
}

- (void)setDateButtons {
    
    self.dateBtns = [[NSMutableArray alloc] init];
    self.weekBtns = [[NSMutableArray alloc] init];
    self.lastWeekBtn = [[UIButton alloc] init];
    self.nextWeekBtn = [[UIButton alloc] init];
    self.lastWeekBtn.frame = CGRectMake(0, 0, 10, 10);
    self.lastWeekBtn.layer.cornerRadius = 15;
    [self.lastWeekBtn setTitle:@"上周" forState:UIControlStateNormal];
    self.lastWeekBtn.titleLabel.font = [UIFont systemFontOfSize: 11.0];
    [self.lastWeekBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.lastWeekBtn addTarget:self action:@selector(decreaseWeek:) forControlEvents:UIControlEventTouchUpInside];
    
    self.lastWeekBtn.layer.masksToBounds = YES;
    self.lastWeekBtn.backgroundColor = [UIColor colorWithRed:116.0/255 green:104.0/255 blue:190.0/255 alpha:1];
    self.nextWeekBtn.frame = CGRectMake(0, 0, 10, 10);
    self.nextWeekBtn.backgroundColor = [UIColor colorWithRed:116.0/255 green:104.0/255 blue:190.0/255 alpha:1];
    self.nextWeekBtn.layer.cornerRadius = 15;
    self.nextWeekBtn.layer.masksToBounds = YES;
    self.nextWeekBtn.titleLabel.font = [UIFont systemFontOfSize: 11.0];
    [self.nextWeekBtn setTitle:@"下周" forState:UIControlStateNormal];
    [self.nextWeekBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.nextWeekBtn addTarget:self action:@selector(increaseWeek:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_nextWeekBtn];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_lastWeekBtn];
    
    self.btnWhichDay = [[NSMutableArray alloc] init];
    self.btnWhichMonth = [[NSMutableArray alloc] init];
    self.btnWhichYear = [[NSMutableArray alloc] init];
    
    NSArray *tmpDay = [NSArray arrayWithObjects:@"11",@"12", @"13",@"14", @"15", @"16", @"17", nil];
    NSArray *tmpMonth = [NSArray arrayWithObjects:@"1", @"1", @"1", @"1", @"1", @"1", @"1", nil];
    NSArray *tmpYear = [NSArray arrayWithObjects:@"2021",@"2021",@"2021", @"2021", @"2021", @"2021", @"2021", nil];
    
    self.btnWhichDay = [[NSMutableArray alloc] init];
    self.btnWhichYear = [[NSMutableArray alloc] init];
    self.btnWhichMonth = [[NSMutableArray alloc] init];
    
    /*for (int i = 0; i < 7; i++) {
     [self.btnWhichDay addObject:tmpDay[i]];
     [self.btnWhichYear addObject:tmpYear[i]];
     [self.btnWhichMonth addObject:tmpMonth[i]];
     }*/
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *nowdate = [NSDate date];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit |
    NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekCalendarUnit | NSWeekOfMonthCalendarUnit | NSWeekOfYearCalendarUnit;
    comps = [calendar components:unitFlags fromDate:nowdate];
    
    NSLog(@"%ld年",(long)[comps year]);
    NSLog(@"%ld月",(long)[comps month]);
    NSLog(@"%ld日",(long)[comps day]);
    NSLog(@"%ld时",(long)[comps hour]);
    NSLog(@"%ld分",(long)[comps minute]);
    NSLog(@"%ld秒",(long)[comps second]);
    NSLog(@"%ld 周几", (long)[comps weekday]);
    
    NSArray *daysOfEachMonth;
    int year = (int)[comps year], month = (int)[comps month], day = (int)[comps day], weekday = (int)[comps weekday] - 1;
    
    if (weekday == 0) {
        weekday = 7;
    }
    
    if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
        daysOfEachMonth = @[@"31", @"29", @"31", @"30", @"31", @"30", @"31", @"31", @"30" , @"31", @"30", @"31"];
    }
    else {
        daysOfEachMonth = @[@"31", @"28", @"31", @"30", @"31", @"30", @"31", @"31", @"30" , @"31", @"30", @"31"];
    }
    
    while (weekday >= 1) {
        weekday = weekday - 1;
        day = day - 1;
        if (day == 0) {
            month = month - 1;
            if (month == 0) {
                month = 12;
                year = year - 1;
            }
            day =[daysOfEachMonth[month - 1] intValue];
        }
    }
    
    puts("----------------------------");
    
    
    for (int i = 0; i <= 6; i++) {
        day = day + 1;
        if (day > [daysOfEachMonth[month - 1] intValue]) {
            month = month + 1;
            if (month > 12) {
                month = 1;
                year = year + 1;
            }
            day = 1;
        }
        [self.btnWhichDay insertObject:[NSString stringWithFormat:@"%d", day] atIndex:i];
        [self.btnWhichMonth insertObject:[NSString stringWithFormat:@"%d", month] atIndex:i];
        [self.btnWhichYear insertObject:[NSString stringWithFormat:@"%d", year] atIndex:i];
    }
    
    puts("----------------------------");
    
    NSArray *titlearray = self.btnWhichDay;
    //NSArray *titlearray = @[@"11",@"12",@"13",@"14",@"15",@"16",@"17"];
    NSArray *datearray = @[@"一",@"二",@"三",@"四",@"五",@"六",@"日"];
    
    int col = 7;
    int margin = 20;
    for (int i = 0; i < titlearray.count; i++) {
        int page = i/col;
        int index = i%col;
        
        UIButton *BtnSearch = [[UIButton alloc]initWithFrame:CGRectMake(margin + index * (SCREEN_WIDTH - (col + 1) * margin)/col + margin * index + 2.5,page + 40,(SCREEN_WIDTH - (col + 1) * margin)/col - 5,(SCREEN_WIDTH - (col + 1) * margin)/col - 5)];
        UIButton *BtnDate = [[UIButton alloc]initWithFrame:CGRectMake(margin + index * (SCREEN_WIDTH - (col + 1) * margin)/col + margin * index,page + 10,(SCREEN_WIDTH - (col + 1) * margin)/col,30 )];
        
        BtnSearch.layer.cornerRadius = (SCREEN_WIDTH - (col + 1) * margin)/col/ 2 - 2.5;
        BtnSearch.layer.masksToBounds = YES;
        BtnSearch.layer.borderWidth = 1;
        BtnSearch.layer.borderColor = [UIColor colorWithRed:220.0/255 green:220.0/255 blue:220.0/255 alpha:1].CGColor;
        BtnSearch.layer.opacity = 1;
        BtnSearch.layer.shadowOffset = CGSizeMake(1, 1);
        BtnSearch.layer.shadowOpacity = 0.8;
        BtnSearch.layer.shadowColor = [UIColor blackColor].CGColor;
        BtnSearch.backgroundColor = [UIColor whiteColor];
        BtnSearch.tag = i;
        BtnSearch.titleLabel.font =  [UIFont systemFontOfSize: 14.0];
        [BtnSearch setTitle:titlearray[i] forState:UIControlStateNormal];
        [BtnSearch setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [BtnSearch setTitleColor:UIColor.whiteColor forState:UIControlStateSelected];
        [BtnSearch addTarget:self action:@selector(SelectBtnSearch:) forControlEvents:UIControlEventTouchUpInside];
        
        BtnDate.layer.cornerRadius = 5;
        BtnDate.layer.masksToBounds = YES;
        BtnDate.backgroundColor = [UIColor clearColor];
        BtnDate.tag = i;
        [BtnDate setTitle:datearray[i] forState:UIControlStateNormal];
        BtnDate.titleLabel.font = [UIFont systemFontOfSize: 14.0];
        [BtnDate setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [BtnDate setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
        
        if (i == 0) {
            BtnSearch.backgroundColor = [UIColor colorWithRed:116.0/255 green:104.0/255 blue:190.0/255 alpha:1];
            BtnSearch.selected = YES;
            //BtnDate.selected = YES;
            self.Selectbutton = BtnSearch;
            self.now_year = [self.btnWhichYear[0] integerValue];
            self.now_month = [self.btnWhichMonth[0] integerValue];
            self.now_day = [titlearray[i] integerValue];
            self.now_week = 1;
        }
        
        [self.dateBtns addObject:BtnSearch];
        [self.SearchTopview addSubview:_dateBtns[i]];
        [self.weekBtns addObject:BtnDate];
        [self.SearchTopview addSubview:_weekBtns[i]];
        
        
    }
    
    self.navigationItem.title = [NSString stringWithFormat:@"%ld.%ld", (long)self.now_year, (long)self.now_month];
    //self.SearchTopview.height = [CalculationTool rowWithcount:titlearray.count andcol:col]*40 + 45;
}

- (void)changeDateBtns:(int) upOrDown {
    
    
    NSArray *daysOfEachMonth;
    int year, month, day;
    
    year = [self.btnWhichYear[0] intValue];
    
    if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
        daysOfEachMonth = @[@"31", @"29", @"31", @"30", @"31", @"30", @"31", @"31", @"30" , @"31", @"30", @"31"];
    }
    else {
        daysOfEachMonth = @[@"31", @"28", @"31", @"30", @"31", @"30", @"31", @"31", @"30" , @"31", @"30", @"31"];
    }
    
    NSLog(@"not ? %d",[_btnWhichDay[0] intValue]);
    
    if (upOrDown == -1) {
        year = [self.btnWhichYear[0] intValue];
        month = [_btnWhichMonth[0] intValue];
        day = [self.btnWhichDay[0] intValue];
        [self.btnWhichDay removeAllObjects];
        [self.btnWhichMonth removeAllObjects];
        [self.btnWhichYear removeAllObjects];
        for (int i = 6; i >= 0; i--) {
            day = day - 1;
            if (day == 0) {
                month = month - 1;
                if (month == 0) {
                    month = 12;
                    year = year - 1;
                }
                day =[daysOfEachMonth[month - 1] intValue];
            }
            [self.btnWhichDay insertObject:[NSString stringWithFormat:@"%d", day] atIndex:0];
            [self.btnWhichMonth insertObject:[NSString stringWithFormat:@"%d", month] atIndex:0];
            [self.btnWhichYear insertObject:[NSString stringWithFormat:@"%d", year] atIndex:0];
        }
    }
    
    else {
        year = [self.btnWhichYear[6] intValue];
        month = [_btnWhichMonth[6] intValue];
        day = [self.btnWhichDay[6] intValue];
        [self.btnWhichDay removeAllObjects];
        [self.btnWhichMonth removeAllObjects];
        [self.btnWhichYear removeAllObjects];
        for (int i = 0; i <= 6; i++) {
            day = day + 1;
            if (day > [daysOfEachMonth[month - 1] intValue]) {
                month = month + 1;
                if (month > 12) {
                    month = 1;
                    year = year + 1;
                }
                day = 1;
            }
            [self.btnWhichDay insertObject:[NSString stringWithFormat:@"%d", day] atIndex:i];
            [self.btnWhichMonth insertObject:[NSString stringWithFormat:@"%d", month] atIndex:i];
            [self.btnWhichYear insertObject:[NSString stringWithFormat:@"%d", year] atIndex:i];
        }
    }
    
    for (int i = 0 ; i < 7; i++) {
        [self.dateBtns[i] setTitle:self.btnWhichDay[i] forState:UIControlStateNormal];
        if (i == 0) {
            [self SelectBtnSearch:_dateBtns[i]];
        }
    }
    
}

- (void)getDailyDatas{
    dispatch_semaphore_t semaphore= dispatch_semaphore_create(0);
    
    //评论区的处理
    //NSString *urlString = [NSString stringWithFormat:@"%@%@", @"http://192.168.199.224:12345/Daily/", self.userID];
    NSString *urlString = [NSString stringWithFormat:@"%@%@%@",self.serverUrl,  @"Daily/", self.userID];
    // NSString *urlString = @"http://192.168.199.224:12345/Daily/1220368815@qq.com";
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";
    request.timeoutInterval = 60;
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                    puts("??????");
                                                    NSError *jsonError;
                                                    
                                                    if (data == nil) {
                                                        dispatch_semaphore_signal(semaphore);
                                                        
                                                        return;
                                                    }
                                                    NSDictionary *jsonDictionaryOrArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
                                                    
                                                    if(jsonError) {
                                                        // check the error description
                                                        NSLog(@"json error : %@", [jsonError localizedDescription]);
                                                    } else{
                                                        // use the jsonDictionaryOrArray
                                                        // NSLog(@"json : %@",jsonDictionaryOrArray);
                                                        if ([[jsonDictionaryOrArray valueForKeyPath:@"response"] isKindOfClass:[NSNull class]]){
                                                            dispatch_semaphore_signal(semaphore);
                                                            
                                                            return;
                                                        }
                                                        
                                                        
                                                        NSArray *items = [jsonDictionaryOrArray valueForKeyPath:@"response"];
                                                        
                                                        self.dailyEventCount = items.count;
                                                        
                                                        self.dailyEventDictionary = jsonDictionaryOrArray;
                                                        NSLog(@"事件数量为%ld", self.dailyEventCount);
                                                    }
                                                    dispatch_semaphore_signal(semaphore);
                                                }];
    [dataTask resume];
    dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
    
    for (int i = 0; i < _dailyEventCount; i++) {
        TimeLineModel*model = [[TimeLineModel alloc]init];
        model.title = self.dailyEventDictionary[@"response"][i][@"Content"];
        NSString* hour = [NSString stringWithFormat:@"%@", self.dailyEventDictionary[@"response"][i][@"Hour"]];
        
        if ([hour length] == 1) {
            hour = [@"0" stringByAppendingString:hour];
        }
        
        NSString *min = [NSString stringWithFormat:@"%@", self.dailyEventDictionary[@"response"][i][@"Min"]];
        
        if ([min length] == 1) {
            min = [@"0" stringByAppendingString:min];
        }
        
        model.time = [NSString stringWithFormat:@"%@:%@",hour, min];
        model.type = @"日常";
        [self.dataArr addObject:model];
    }
    
}

- (void) getWeekDatas {
    dispatch_semaphore_t semaphore= dispatch_semaphore_create(0);
    
    //评论区的处理
    //NSString *urlString = [NSString stringWithFormat:@"%@%@", @"172.18.42.103:12345/Daily/1220298052", @""];
    //NSString *urlString = [NSString stringWithFormat:@"%@%@", @"http://192.168.199.224:12345/Weekly/", self.userID];
    NSString *urlString = [NSString stringWithFormat:@"%@%@%@",self.serverUrl,  @"Weekly/", self.userID];
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";
    request.timeoutInterval = 60;
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                    NSError *jsonError;
                                                    
                                                    if (data == nil) {
                                                        dispatch_semaphore_signal(semaphore);
                                                        
                                                        return;
                                                    }
                                                    
                                                    NSDictionary *jsonDictionaryOrArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
                                                    if(jsonError) {
                                                        // check the error description
                                                        NSLog(@"json error : %@", [jsonError localizedDescription]);
                                                    } else {
                                                        // use the jsonDictionaryOrArray
                                                        //NSLog(@"json : %@",jsonDictionaryOrArray);
                                                        
                                                        if ([[jsonDictionaryOrArray valueForKeyPath:@"response"] isKindOfClass:[NSNull class]]){
                                                            dispatch_semaphore_signal(semaphore);
                                                            
                                                            return;
                                                        }
                                                        
                                                        NSArray *items = [jsonDictionaryOrArray valueForKeyPath:@"response"];
                                                        
                                                        self.weekEventCount = items.count;
                                                        
                                                        self.weekEventDictionary = jsonDictionaryOrArray;
                                                        NSLog(@"事件数量为%ld", self.weekEventCount);
                                                    }
                                                    dispatch_semaphore_signal(semaphore);
                                                }];
    [dataTask resume];
    dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
    
    for (int i = 0; i < self.weekEventCount; i++) {
        NSString *weekday = [NSString stringWithFormat:@"%@", self.weekEventDictionary[@"response"][i][@"Week"]];
        if ([weekday isEqualToString:[NSString stringWithFormat:@"%ld", (long)self.now_week]]) {
            TimeLineModel*model = [[TimeLineModel alloc]init];
            model.title = self.weekEventDictionary[@"response"][i][@"Content"];
            NSString* hour = [NSString stringWithFormat:@"%@", self.weekEventDictionary[@"response"][i][@"Hour"]];
            
            if ([hour length] == 1) {
                hour = [@"0" stringByAppendingString:hour];
            }
            
            NSString *min = [NSString stringWithFormat:@"%@", self.weekEventDictionary[@"response"][i][@"Min"]];
            
            if ([min length] == 1) {
                min = [@"0" stringByAppendingString:min];
            }
            
            model.time = [NSString stringWithFormat:@"%@:%@",hour, min];
            model.type = @"周常";
            [self.dataArr addObject:model];
        }
    }
    
}

- (void) getOnetimeDatas {
    self.firstOneTimeEvent = @"无待办事件";
    
    dispatch_semaphore_t semaphore= dispatch_semaphore_create(0);
    
    //评论区的处理
    //NSString *urlString = [NSString stringWithFormat:@"%@%@", @"172.18.42.103:12345/Daily/1220298052", @""];
    NSString *urlString = [NSString stringWithFormat:@"%@%@%@",self.serverUrl,  @"Onetime/", self.userID];
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";
    request.timeoutInterval = 60;
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                    NSError *jsonError;
                                                    
                                                    if (data == nil) {
                                                        dispatch_semaphore_signal(semaphore);
                                                        return;
                                                    }
                                                    
                                                    NSDictionary *jsonDictionaryOrArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
                                                    if(jsonError) {
                                                        // check the error description
                                                        NSLog(@"json error : %@", [jsonError localizedDescription]);
                                                    } else {
                                                        // use the jsonDictionaryOrArray
                                                        //NSLog(@"json : %@",jsonDictionaryOrArray);
                                                        if ([[jsonDictionaryOrArray valueForKeyPath:@"response"] isKindOfClass:[NSNull class]]) {
                                                            dispatch_semaphore_signal(semaphore);
                                                            
                                                            return;
                                                        }
                                                        
                                                        
                                                        NSArray *items = [jsonDictionaryOrArray valueForKeyPath:@"response"];
                                                        
                                                        
                                                        self.oneTimeEventCount = items.count;
                                                        
                                                        self.oneTimeEventDictionary = jsonDictionaryOrArray;
                                                        NSLog(@"事件数量为%ld", self.oneTimeEventCount);
                                                    }
                                                    dispatch_semaphore_signal(semaphore);
                                                }];
    [dataTask resume];
    dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
    
    bool flag = false;
    
    
    for (int i = 0; i < _oneTimeEventCount; i++) {
        NSString *day = [NSString stringWithFormat:@"%@", self.oneTimeEventDictionary[@"response"][i][@"Day"]];
        NSString *month = [NSString stringWithFormat:@"%@", self.oneTimeEventDictionary[@"response"][i][@"Month"]];
        NSString *year = [NSString stringWithFormat:@"%@", self.oneTimeEventDictionary[@"response"][i][@"Year"]];
        if ([day isEqualToString:[NSString stringWithFormat:@"%ld", (long)self.now_day]] && [month isEqualToString:[NSString stringWithFormat:@"%ld", (long)self.now_month]] && [year isEqualToString:[NSString stringWithFormat:@"%ld", (long)self.now_year]]) {
            
            
            TimeLineModel*model = [[TimeLineModel alloc]init];
            model.title = self.oneTimeEventDictionary[@"response"][i][@"Content"];
            NSString* hour = [NSString stringWithFormat:@"%@", self.oneTimeEventDictionary[@"response"][i][@"Hour"]];
            
            if (!flag) {
                flag = true;
                self.firstOneTimeEvent = model.title;
            }
            if ([hour length] == 1) {
                hour = [@"0" stringByAppendingString:hour];
            }
            
            NSString *min = [NSString stringWithFormat:@"%@", self.oneTimeEventDictionary[@"response"][i][@"Min"]];
            
            if ([min length] == 1) {
                min = [@"0" stringByAppendingString:min];
            }
            
            model.time = [NSString stringWithFormat:@"%@:%@",hour, min];
            model.type = @"单次";
            [self.dataArr addObject:model];
        }
        //if (_oneTimeEventDictionary[@"response"][i][])
    }
}

-  (void) viewDidAppear:(BOOL)animated {
    [self viewDidLoad];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    headimageModel *current_head_image = [headimageModel shareInstance];
    _serverUrl = current_head_image.host_str;
    // headimageModel *current_head_image = [headimageModel shareInstance];
    if ([current_head_image.ID isEqualToString: @"notlogin"]) {
        
        _notlogin_pic = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 4, SCREEN_HEIGHT / 4, SCREEN_WIDTH / 2, 200)];
        _notlogin_pic.backgroundColor = [UIColor colorWithPatternImage:[[UIImage imageNamed:@"warning.png"] TransformtoSize:CGSizeMake(200, 200)]];
        [self.view addSubview:_notlogin_pic];
        _notlogin_label = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 4, 2* SCREEN_HEIGHT / 3, 200, 40)];
        _notlogin_label.text = @"请先登录！";
        
        _notlogin_label.textAlignment = NSTextAlignmentCenter;
        [self.view addSubview:_notlogin_label];
        return;
    }
    [_notlogin_pic removeFromSuperview];
    [_notlogin_label removeFromSuperview];
    self.userID = current_head_image.ID;
    //self.userID = @"1220298052";
    self.navigationItem.title = @"日程";
    [self.view setBackgroundColor:[UIColor colorWithRed:245.0/255 green:245.0/255 blue:245.0/255 alpha:1]];
    [self setDateButtons];
    // self.automaticallyAdjustsScrollViewInsets = YES;
    
    /*self.encourageTextView = [[UITextView alloc] initWithFrame:CGRectMake(1 * SCREEN_WIDTH / 5, 1 * SCREEN_HEIGHT/ 10, 3 * SCREEN_WIDTH / 5, 50)];
     self.encourageTextView.text = @"每一个不曾起舞的日子,\n都是对生命的辜负";
     self.encourageTextView.textAlignment = NSTextAlignmentCenter;
     self.encourageTextView.font = [UIFont systemFontOfSize:15];
     [self.view addSubview:self.encourageTextView];*/
    
    //阴影部分
    //self.userID = @"1220298052";
    self.eventview = [[UIView alloc] initWithFrame:CGRectMake(30, 125, SCREEN_WIDTH - 60, SCREEN_HEIGHT - 300)];
    self.eventview.layer.shadowOpacity = 0.5;
    self.eventview.layer.shadowColor = [UIColor grayColor].CGColor;
    self.eventview.layer.shadowRadius = 10;// 阴影扩散的范围控制
    
    //边框部分
    self.eventview.layer.masksToBounds = YES;
    self.eventview.layer.cornerRadius = self.eventview.frame.size.width / 16;
    self.eventview.layer.borderColor = [UIColor colorWithRed:220.0/255 green:220.0/255 blue:220.0/255 alpha:0.5].CGColor;
    self.eventview.layer.borderWidth = 1;//边框宽度
    
    [self.view addSubview:self.eventview];
    
    
    self.warnView = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 5, 3 * SCREEN_HEIGHT / 4, 3 * SCREEN_WIDTH / 5, SCREEN_HEIGHT / 8)];
    self.warnTextView = [[UITextView alloc] initWithFrame:CGRectMake(2.9 * SCREEN_WIDTH / 15, 0, 100, 30)];
    //self.warnTextView.layer.borderWidth = 1;
    self.warnTextView.scrollEnabled = NO;
    self.warnTextView.userInteractionEnabled = NO;
    self.warnTextView.font = [UIFont systemFontOfSize:15];
    //self.warnView.layer.shadowOpacity = 1;
    // self.warnView.layer.shadowColor = [UIColor grayColor].CGColor;
    // self.warnView.layer.shadowRadius = 3;// 阴影扩散的范围控制
    
    //边框部分
    self.warnView.layer.masksToBounds = YES;
    self.warnView.layer.cornerRadius = self.warnView.frame.size.width / 16;
    self.warnView.layer.borderColor = [UIColor colorWithRed:220.0/255 green:220.0/255 blue:220.0/255 alpha:0.5].CGColor;//边框颜色
    self.warnView.layer.borderWidth = 0.5;//边框宽度
    self.warnView.backgroundColor = [UIColor whiteColor];
    
    self.warnTextView.text = @"今日待办";
    [self.warnView addSubview:self.warnTextView];
    
    puts("!!!!!!!!!!!!!1");
    
    
    [self.view addSubview:self.warnView];
    puts("!!!!!!!!!!!!!2");
    
    self.timeLine = [[QinzTimeLine alloc]init];
    puts("!!!!!!!!!!!!!3");
    
    
    self.dataArr = [[NSMutableArray alloc]init];
    puts("!!!!!!!!!!!!!4");
    
    [self getDailyDatas];
    
    puts("!!!!!!!!!!!!!5");
    
    [self getOnetimeDatas];
    
    puts("!!!!!!!!!!!!!6");
    
    [self getWeekDatas];
    
    puts("!!!!!!!!!!!!!7");
    
    
    
    self.firstOneTimeEventView = [[UITextView alloc] initWithFrame:CGRectMake(30, 40, 157, 50)];
    self.firstOneTimeEventView.text = self.firstOneTimeEvent;
    self.firstOneTimeEventView.font = [UIFont systemFontOfSize:20];
    [self.firstOneTimeEventView setFont:[UIFont fontWithName:@"Helvetica-Bold" size:15]];
    // self.firstOneTimeEventView.layer.borderWidth = 5;
    self.firstOneTimeEventView.textAlignment = NSTextAlignmentCenter;
    self.firstOneTimeEventView.textColor = [UIColor colorWithRed:116.0/255 green:104.0/255 blue:190.0/255 alpha:1];
    self.firstOneTimeEventView.userInteractionEnabled = NO;
    [self.warnView addSubview:self.firstOneTimeEventView];
    
    puts("!!!!!!!!!!!!!");
    
    
    [self.dataArr sortUsingComparator:^NSComparisonResult(TimeLineModel *c1, TimeLineModel *c2) {
        NSComparisonResult result = [c1.time compare:c2.time];
        return result;
    }];
    
    [self.timeLine setSuperView:self.eventview DataArr:self.dataArr];
    [self.view addSubview:self.SearchTopview];
    
    
}

-(void)setData{
    
    self.dataArr = [[NSMutableArray alloc]init];
    
    NSArray *textArray = @[@"电子政务",
                           @"午饭时间",
                           @"现代操作系统",
                           @"区块链",
                           @"晚饭"
                           , @"锻炼",
                           @"睡觉"];
    
    for (int i = 0; i<textArray.count; i++) {
        TimeLineModel*model = [[TimeLineModel alloc]init];
        model.title = textArray[i];
        model.time = [NSString stringWithFormat:@"12:%d",i*6];
        [self.dataArr addObject:model];
    }
    
}





@end
